// 全局应用对象
const AttendanceApp = {
    // API基础URL
    apiBase: '/x_attendance_assemble_control/jaxrs',
    
    // 当前用户信息
    currentUser: null,
    
    // 当前页面
    currentPage: 'dashboard',
    
    // 初始化应用
    init() {
        this.initEventListeners();
        this.loadDashboardData();
        this.startAutoRefresh();
    },
    
    // 初始化事件监听器
    initEventListeners() {
        // 侧边栏菜单点击
        document.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const page = e.currentTarget.dataset.page;
                this.switchPage(page);
            });
        });
        
        // 移动端菜单切换
        const menuToggle = document.querySelector('.menu-toggle');
        const sidebar = document.querySelector('.sidebar');
        
        if (menuToggle) {
            menuToggle.addEventListener('click', () => {
                sidebar.classList.toggle('show');
            });
        }
        
        // 模态框关闭
        document.querySelector('.modal-close').addEventListener('click', () => {
            this.hideModal();
        });
        
        document.querySelector('#modal-overlay').addEventListener('click', (e) => {
            if (e.target === e.currentTarget) {
                this.hideModal();
            }
        });
        
        // ESC键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.hideModal();
            }
        });
    },
    
    // 切换页面
    switchPage(page) {
        // 更新菜单状态
        document.querySelectorAll('.menu-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-page="${page}"]`).classList.add('active');
        
        // 更新页面内容
        document.querySelectorAll('.page').forEach(p => {
            p.classList.remove('active');
        });
        document.getElementById(`${page}-page`).classList.add('active');
        
        // 更新页面标题
        const titles = {
            dashboard: '仪表盘',
            fingerprint: '指纹采集',
            devices: '设备管理',
            attendance: '考勤记录',
            employees: '员工管理',
            sync: '数据同步',
            settings: '系统设置'
        };
        document.querySelector('.page-title').textContent = titles[page] || page;
        
        this.currentPage = page;
        
        // 加载页面数据
        this.loadPageData(page);
        
        // 移动端自动关闭侧边栏
        if (window.innerWidth <= 768) {
            document.querySelector('.sidebar').classList.remove('show');
        }
    },
    
    // 加载页面数据
    loadPageData(page) {
        switch (page) {
            case 'dashboard':
                this.loadDashboardData();
                break;
            case 'fingerprint':
                FingerprintManager.init();
                break;
            case 'devices':
                DeviceManager.loadDevices();
                break;
            case 'attendance':
                AttendanceManager.init();
                break;
            case 'employees':
                this.loadEmployeesData();
                break;
            case 'sync':
                this.loadSyncData();
                break;
            case 'settings':
                this.loadSettingsData();
                break;
        }
    },
    
    // 加载仪表盘数据
    async loadDashboardData() {
        try {
            this.showLoading();
            
            // 并行加载统计数据
            const [employeeStats, deviceStats, attendanceStats, fingerprintStats] = await Promise.all([
                this.api('/employee/count'),
                this.api('/device/stats'),
                this.api('/attendance/today'),
                this.api('/fingerprint/count')
            ]);
            
            // 更新统计卡片
            document.getElementById('total-employees').textContent = employeeStats.data || 0;
            document.getElementById('online-devices').textContent = deviceStats.data?.online || 0;
            document.getElementById('today-records').textContent = attendanceStats.data || 0;
            document.getElementById('total-fingerprints').textContent = fingerprintStats.data || 0;
            
            // 加载考勤趋势图表
            await this.loadAttendanceChart();
            
            // 加载最近活动
            await this.loadRecentActivities();
            
            this.hideLoading();
        } catch (error) {
            console.error('加载仪表盘数据失败:', error);
            this.hideLoading();
            this.showNotification('加载数据失败', 'error');
        }
    },
    
    // 加载考勤趋势图表
    async loadAttendanceChart() {
        try {
            const response = await this.api('/attendance/trend?days=7');
            const data = response.data || [];
            
            const ctx = document.getElementById('attendance-chart');
            if (ctx && window.Chart) {
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: data.map(item => item.date),
                        datasets: [{
                            label: '打卡人次',
                            data: data.map(item => item.count),
                            borderColor: '#667eea',
                            backgroundColor: 'rgba(102, 126, 234, 0.1)',
                            borderWidth: 3,
                            fill: true,
                            tension: 0.4
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                grid: {
                                    color: 'rgba(0,0,0,0.1)'
                                }
                            },
                            x: {
                                grid: {
                                    display: false
                                }
                            }
                        }
                    }
                });
            }
        } catch (error) {
            console.error('加载考勤趋势图表失败:', error);
        }
    },
    
    // 加载最近活动
    async loadRecentActivities() {
        try {
            const response = await this.api('/activity/recent?limit=10');
            const activities = response.data || [];
            
            const container = document.getElementById('recent-activities');
            container.innerHTML = '';
            
            if (activities.length === 0) {
                container.innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">暂无活动记录</p>';
                return;
            }
            
            activities.forEach(activity => {
                const item = document.createElement('div');
                item.className = 'activity-item';
                
                const iconClass = this.getActivityIcon(activity.type);
                const iconColor = this.getActivityColor(activity.type);
                
                item.innerHTML = `
                    <div class="activity-icon" style="background-color: ${iconColor}">
                        <i class="${iconClass}"></i>
                    </div>
                    <div class="activity-info">
                        <p>${activity.description}</p>
                        <small>${this.formatTime(activity.time)}</small>
                    </div>
                `;
                
                container.appendChild(item);
            });
        } catch (error) {
            console.error('加载最近活动失败:', error);
        }
    },
    
    // 获取活动图标
    getActivityIcon(type) {
        const icons = {
            fingerprint: 'fas fa-fingerprint',
            device: 'fas fa-desktop',
            attendance: 'fas fa-clock',
            sync: 'fas fa-sync',
            employee: 'fas fa-user'
        };
        return icons[type] || 'fas fa-info-circle';
    },
    
    // 获取活动颜色
    getActivityColor(type) {
        const colors = {
            fingerprint: '#667eea',
            device: '#f093fb',
            attendance: '#4facfe',
            sync: '#43e97b',
            employee: '#764ba2'
        };
        return colors[type] || '#6c757d';
    },
    
    // 格式化时间
    formatTime(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60000) { // 1分钟内
            return '刚刚';
        } else if (diff < 3600000) { // 1小时内
            return `${Math.floor(diff / 60000)}分钟前`;
        } else if (diff < 86400000) { // 1天内
            return `${Math.floor(diff / 3600000)}小时前`;
        } else {
            return date.toLocaleDateString();
        }
    },
    
    // 开始自动刷新
    startAutoRefresh() {
        // 每30秒刷新一次同步状态
        setInterval(() => {
            this.updateSyncStatus();
        }, 30000);
        
        // 每5分钟刷新一次仪表盘数据
        setInterval(() => {
            if (this.currentPage === 'dashboard') {
                this.loadDashboardData();
            }
        }, 300000);
    },
    
    // 更新同步状态
    async updateSyncStatus() {
        try {
            const response = await this.api('/sync/status');
            const status = response.data;
            
            const indicator = document.querySelector('.sync-indicator');
            const text = document.querySelector('.sync-status span');
            
            if (status?.healthy) {
                indicator.style.color = '#28a745';
                text.textContent = '同步正常';
            } else {
                indicator.style.color = '#dc3545';
                text.textContent = '同步异常';
            }
        } catch (error) {
            console.error('更新同步状态失败:', error);
        }
    },
    
    // API请求封装
    async api(endpoint, options = {}) {
        const url = this.apiBase + endpoint;
        const defaultOptions = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        };
        
        const finalOptions = { ...defaultOptions, ...options };
        
        try {
            const response = await fetch(url, finalOptions);
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            return data;
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    },
    
    // 显示加载指示器
    showLoading() {
        document.getElementById('loading-overlay').classList.add('show');
    },
    
    // 隐藏加载指示器
    hideLoading() {
        document.getElementById('loading-overlay').classList.remove('show');
    },
    
    // 显示模态框
    showModal(title, content, buttons = []) {
        document.getElementById('modal-title').textContent = title;
        document.getElementById('modal-body').innerHTML = content;
        
        const footer = document.getElementById('modal-footer');
        footer.innerHTML = '';
        
        buttons.forEach(button => {
            const btn = document.createElement('button');
            btn.className = `btn ${button.class || 'btn-secondary'}`;
            btn.textContent = button.text;
            btn.onclick = button.onclick;
            footer.appendChild(btn);
        });
        
        document.getElementById('modal-overlay').classList.add('show');
    },
    
    // 隐藏模态框
    hideModal() {
        document.getElementById('modal-overlay').classList.remove('show');
    },
    
    // 显示通知
    showNotification(message, type = 'info', duration = 3000) {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <i class="fas fa-${this.getNotificationIcon(type)}"></i>
            <span>${message}</span>
            <button class="notification-close">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            padding: 15px 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            z-index: 4000;
            min-width: 300px;
            animation: slideInRight 0.3s ease;
            border-left: 4px solid ${this.getNotificationColor(type)};
        `;
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 关闭按钮事件
        notification.querySelector('.notification-close').onclick = () => {
            this.removeNotification(notification);
        };
        
        // 自动关闭
        if (duration > 0) {
            setTimeout(() => {
                this.removeNotification(notification);
            }, duration);
        }
    },
    
    // 移除通知
    removeNotification(notification) {
        notification.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    },
    
    // 获取通知图标
    getNotificationIcon(type) {
        const icons = {
            success: 'check-circle',
            error: 'exclamation-circle',
            warning: 'exclamation-triangle',
            info: 'info-circle'
        };
        return icons[type] || 'info-circle';
    },
    
    // 获取通知颜色
    getNotificationColor(type) {
        const colors = {
            success: '#28a745',
            error: '#dc3545',
            warning: '#ffc107',
            info: '#17a2b8'
        };
        return colors[type] || '#17a2b8';
    },
    
    // 确认对话框
    confirm(message, onConfirm, onCancel) {
        this.showModal('确认操作', `<p>${message}</p>`, [
            {
                text: '取消',
                class: 'btn-secondary',
                onclick: () => {
                    this.hideModal();
                    if (onCancel) onCancel();
                }
            },
            {
                text: '确认',
                class: 'btn-primary',
                onclick: () => {
                    this.hideModal();
                    if (onConfirm) onConfirm();
                }
            }
        ]);
    },
    
    // 格式化日期
    formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
        if (!date) return '';
        
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        
        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
    },
    
    // 加载员工数据（占位符）
    loadEmployeesData() {
        console.log('加载员工数据...');
    },
    
    // 加载同步数据（占位符）
    loadSyncData() {
        console.log('加载同步数据...');
    },
    
    // 加载设置数据（占位符）
    loadSettingsData() {
        console.log('加载设置数据...');
    }
};

// 添加通知动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            opacity: 0;
            transform: translateX(100%);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }
    
    @keyframes slideOutRight {
        from {
            opacity: 1;
            transform: translateX(0);
        }
        to {
            opacity: 0;
            transform: translateX(100%);
        }
    }
`;
document.head.appendChild(style);

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    AttendanceApp.init();
});

